package com.cskaoyan.service;

import com.cskaoyan.bean.BO.OrderCommentBo;
import com.cskaoyan.bean.BO.OrderSubmitBo;
import com.cskaoyan.bean.PO.*;
import com.cskaoyan.bean.VO.*;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.mapper.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName WxOrderServiceImpl
 * @Description TODO
 * @Author ke
 * @Date 2022/8/16 14:46
 * @Version 1.0
 */
@Service
public class WxOrderServiceImpl implements WxOrderService {


    @Autowired
    MarketOrderMapper orderMapper;

    @Autowired
    MarketUserMapper userMapper;

    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;

    @Autowired
    MarketCommentMapper commentMapper;

    @Autowired
    MarketAddressMapper addressMapper;

    @Autowired
    MarketCouponUserMapper couponUserMapper;

    @Autowired
    MarketCouponMapper couponMapper;

    @Autowired
    MarketCartMapper cartMapper;

    @Autowired
    MarketGoodsMapper goodsMapper;


    @Override
    public CommonData<WxOrderListVo> list(String username,Integer showType,Integer page,Integer limit) {
        // 在登录的时候会在session中保存username,先用username获取userId
        MarketUserExample userExample = new MarketUserExample();
        MarketUserExample.Criteria userExampleCriteria = userExample.createCriteria();
        userExampleCriteria.andUsernameEqualTo(username);

        List<MarketUser> marketUsers = userMapper.selectByExample(userExample);
        MarketUser marketUser = marketUsers.get(0);
        Integer userId = marketUser.getId();

        // 根据userId在Order表中就可以查相关的订单
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria orderExampleCriteria = orderExample.createCriteria();
        orderExampleCriteria.andUserIdEqualTo(userId);
        Short[] statusArray={101,201,301,401,202};

        orderExampleCriteria.andOrderStatusIn(Arrays.asList(statusArray));

        orderExampleCriteria.andDeletedEqualTo(false);




        /*  0:全部
            1:待付款
            2:待发货
            3:待收货
            4:待评价*/


        /* 101:未付款 102:用户取消 103:系统取消 201:已付款 202:申请退款 203:已退款 301:已发货 401:用户收货
         402:系统收货*/
        if (showType == 1) {
            Short status=101;
            orderExampleCriteria.andOrderStatusEqualTo(status);
        }

        if (showType == 2) {
            Short status=201;
            orderExampleCriteria.andOrderStatusEqualTo(status);
        }

        if (showType == 3) {
            Short status=301;
            orderExampleCriteria.andOrderStatusEqualTo(status);
        }

        if (showType == 4) {
            Short[] status=new Short[]{401,402};
            List<Short> statusList = Arrays.asList(status);
            orderExampleCriteria.andOrderStatusIn(statusList);
            // Short num=0;
            // orderExampleCriteria.andCommentsGreaterThan(num);
        }


        // 查询前先进行分页操作
        PageHelper.startPage(page,limit);

        // 这是查询出来的list
        List<MarketOrder> orders = orderMapper.selectByExample(orderExample);
        // 这是一会要放进CommonData中的list
        List<WxOrderListVo> vos=new LinkedList<>();

        for (MarketOrder po : orders) {
            WxOrderListVo vo = new WxOrderListVo();
            vo.setActualPrice(po.getActualPrice());
            vo.setAftersaleStatus(po.getAftersaleStatus());
            // 根据orderId再查询商品信息
            Integer orderId = po.getId();
            MarketOrderGoodsExample example = new MarketOrderGoodsExample();
            MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
            criteria.andOrderIdEqualTo(orderId);
            List<MarketOrderGoods> goodsPos = orderGoodsMapper.selectByExample(example);
            // 给vo中的goodsList赋值
            List<WxOrderGoodsVo> goodsVos=new LinkedList<>();
            for (MarketOrderGoods goodsPo : goodsPos) {
                WxOrderGoodsVo goodsVo = new WxOrderGoodsVo();
                goodsVo.setGoodsName(goodsPo.getGoodsName());
                goodsVo.setId(goodsPo.getId());
                goodsVo.setNumber(goodsPo.getNumber());
                goodsVo.setPicUrl(goodsPo.getPicUrl());
                goodsVo.setPrice(goodsPo.getPrice());
                goodsVo.setSpecifications(goodsPo.getSpecifications());
                goodsVos.add(goodsVo);
            }
            vo.setGoodsList(goodsVos);
            vo.setId(po.getId());
            // 查询handleOption


            /*售后状态，0是可申请，1是用户已申请，2是管理员审核通过，
            3是管理员退款成功，4是管理员审核拒绝，5是用户已取消*/




            vo.setIsGroupin(false);
            // 这啥啊这是,不会写啊,先全false吧
            vo.setOrderSn(po.getOrderSn());

            /* 101:未付款 102:用户取消 103:系统取消 201:已付款 202:申请退款 203:已退款 301:已发货 401:用户收货
         402:系统收货*/

            handleOptionVo handleOptionVo = new handleOptionVo();


            Short orderStatus = po.getOrderStatus();

            if (orderStatus==101){
                vo.setOrderStatusText("待付款");


                handleOptionVo.setAftersale(false);
                handleOptionVo.setCancel(true);
                handleOptionVo.setComment(false);
                handleOptionVo.setConfirm(false);
                handleOptionVo.setDelete(false);
                handleOptionVo.setPay(true);
                handleOptionVo.setRebuy(false);
                handleOptionVo.setRefund(false);
                vo.setHandleOption(handleOptionVo);
            }

            if (orderStatus==201){
                vo.setOrderStatusText("待发货");
                handleOptionVo.setAftersale(false);
                handleOptionVo.setCancel(false);
                handleOptionVo.setComment(false);
                handleOptionVo.setConfirm(false);
                handleOptionVo.setDelete(false);
                handleOptionVo.setPay(false);
                handleOptionVo.setRebuy(false);
                handleOptionVo.setRefund(true);
                vo.setHandleOption(handleOptionVo);
            }

            if (orderStatus==301){
                vo.setOrderStatusText("待收货");
                handleOptionVo.setAftersale(false);
                handleOptionVo.setCancel(false);
                handleOptionVo.setComment(false);
                handleOptionVo.setConfirm(true);
                handleOptionVo.setDelete(false);
                handleOptionVo.setPay(false);
                handleOptionVo.setRebuy(false);
                handleOptionVo.setRefund(false);
                vo.setHandleOption(handleOptionVo);
            }

            if (orderStatus==401){
                vo.setOrderStatusText("待评价");
                handleOptionVo.setAftersale(true);
                handleOptionVo.setCancel(false);
                handleOptionVo.setComment(true);
                handleOptionVo.setConfirm(false);
                handleOptionVo.setDelete(false);
                handleOptionVo.setPay(false);
                handleOptionVo.setRebuy(true);
                handleOptionVo.setRefund(false);
                vo.setHandleOption(handleOptionVo);
            }

            if (orderStatus==202){
                vo.setOrderStatusText("订单取消,退款中");
                handleOptionVo.setAftersale(false);
                handleOptionVo.setCancel(false);
                handleOptionVo.setComment(false);
                handleOptionVo.setConfirm(false);
                handleOptionVo.setDelete(false);
                handleOptionVo.setPay(false);
                handleOptionVo.setRebuy(false);
                handleOptionVo.setRefund(false);
                vo.setHandleOption(handleOptionVo);
            }


            vos.add(vo);

        }


        PageInfo pageInfo = new PageInfo(vos);

        CommonData data = CommonData.data(pageInfo);


        return data;
    }

    @Override
    public WxOrderDetailVo detail(Integer orderId) {

        // 查出order的po
        MarketOrder po = orderMapper.selectByPrimaryKey(orderId);
        // 查出orderGoods的po
        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> orderGoods = orderGoodsMapper.selectByExample(example);

        WxOrderDetailVo vo = new WxOrderDetailVo();

        // 不知道里面写啥
        vo.setExpressInfo(null);

        vo.setOrderGoods(orderGoods);

        handleOptionVo handleOptionVo = new handleOptionVo();
        Short orderStatus = po.getOrderStatus();


        /* 101:未付款 102:用户取消 103:系统取消 201:已付款 202:申请退款 203:已退款 301:已发货 401:用户收货
         402:系统收货*/

        if (orderStatus==101){
            handleOptionVo.setAftersale(false);
            handleOptionVo.setCancel(true);
            handleOptionVo.setComment(false);
            handleOptionVo.setConfirm(false);
            handleOptionVo.setDelete(false);
            handleOptionVo.setPay(true);
            handleOptionVo.setRebuy(false);
            handleOptionVo.setRefund(false);
        }

        if (orderStatus==201){

            handleOptionVo.setAftersale(false);
            handleOptionVo.setCancel(false);
            handleOptionVo.setComment(false);
            handleOptionVo.setConfirm(false);
            handleOptionVo.setDelete(false);
            handleOptionVo.setPay(false);
            handleOptionVo.setRebuy(false);
            handleOptionVo.setRefund(true);

        }

        if (orderStatus==301){

            handleOptionVo.setAftersale(false);
            handleOptionVo.setCancel(false);
            handleOptionVo.setComment(false);
            handleOptionVo.setConfirm(true);
            handleOptionVo.setDelete(false);
            handleOptionVo.setPay(false);
            handleOptionVo.setRebuy(false);
            handleOptionVo.setRefund(false);

        }

        if (orderStatus==401){

            handleOptionVo.setAftersale(true);
            handleOptionVo.setCancel(false);
            handleOptionVo.setComment(true);
            handleOptionVo.setConfirm(false);
            handleOptionVo.setDelete(false);
            handleOptionVo.setPay(false);
            handleOptionVo.setRebuy(true);
            handleOptionVo.setRefund(false);

        }

        String orderStatusText="";

        WxOrderInfoVo info = new WxOrderInfoVo(po.getActualPrice(),po.getAddTime(),po.getAddress(),po.getAftersaleStatus(),po.getConsignee(),po.getCouponPrice(),po.getShipChannel(),po.getShipChannel(),po.getShipSn(),po.getFreightPrice(),po.getGoodsPrice(),handleOptionVo,po.getId(),po.getMessage(),po.getMobile(),po.getOrderSn(),orderStatusText);


        vo.setOrderInfo(info);


        return vo;
    }

    @Override
    public int refund(Integer orderId) {
        /* 101:未付款 102:用户取消 103:系统取消 201:已付款 202:申请退款 203:已退款 301:已发货 401:用户收货
         402:系统收货*/
        MarketOrder order = new MarketOrder();
        order.setId(orderId);
        Short status=202;
        order.setOrderStatus(status);
        orderMapper.updateByPrimaryKeySelective(order);
        return 0;
    }

    @Override
    public int delete(Integer orderId) {
        MarketOrder order = new MarketOrder();
        order.setId(orderId);
        order.setDeleted(true);
        orderMapper.updateByPrimaryKeySelective(order);
        return 0;
    }

    @Override
    public int confirm(Integer orderId) {
        MarketOrder order = new MarketOrder();
        order.setId(orderId);


        Short status=401;
        order.setOrderStatus(status);
        orderMapper.updateByPrimaryKeySelective(order);
        return 0;
    }

    @Override
    public int comment(OrderCommentBo bo) {
        String content = bo.getContent();
        Integer orderGoodsId = bo.getOrderGoodsId();
        MarketOrderGoods marketOrderGoods = orderGoodsMapper.selectByPrimaryKey(orderGoodsId);
        Integer valueId = marketOrderGoods.getOrderId();
        Short star = bo.getStar();
        MarketComment marketComment = new MarketComment();
        marketComment.setValueId(valueId);
        marketComment.setContent(content);
        // 拿到username
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");

        MarketUserExample example = new MarketUserExample();

        MarketUserExample.Criteria criteria = example.createCriteria();

        criteria.andUsernameEqualTo(username);

        List<MarketUser> marketUsers = userMapper.selectByExample(example);

        MarketUser marketUser = marketUsers.get(0);

        Integer userId = marketUser.getId();


        marketComment.setUserId(userId);

        marketComment.setHasPicture(bo.getHasPicture());

        marketComment.setPicUrls(bo.getPicUrls());

        marketComment.setStar(star);

        marketComment.setAddTime(new Date());

        marketComment.setDeleted(false);

        commentMapper.insertSelective(marketComment);

        Integer commentId = marketComment.getId();

        MarketOrderGoods goods = new MarketOrderGoods();
        goods.setId(orderGoodsId);
        goods.setComment(commentId);
        orderGoodsMapper.updateByPrimaryKeySelective(goods);


        return 0;
    }

    @Override
    public int cancel(Integer orderId) {
      /* 101:未付款 102:用户取消 103:系统取消 201:已付款 202:申请退款 203:已退款 301:已发货 401:用户收货
         402:系统收货*/
        MarketOrder order = new MarketOrder();
        order.setId(orderId);
        Short status=102;
        order.setOrderStatus(status);
        orderMapper.updateByPrimaryKeySelective(order);
        return 0;
    }

    @Override
    public int prepay(Integer orderId) {
      /* 101:未付款 102:用户取消 103:系统取消 201:已付款 202:申请退款 203:已退款 301:已发货 401:用户收货
         402:系统收货*/
        MarketOrder order = new MarketOrder();
        order.setId(orderId);
        Short status=201;
        order.setOrderStatus(status);
        orderMapper.updateByPrimaryKeySelective(order);
        return 0;
    }

    @Override
    public MarketOrderGoods goods(Integer orderId, Integer goodsId) {
        MarketOrderGoodsExample example = new MarketOrderGoodsExample();

        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();

        criteria.andOrderIdEqualTo(orderId);
        criteria.andGoodsIdEqualTo(goodsId);

        List<MarketOrderGoods> goodsList = orderGoodsMapper.selectByExample(example);

        MarketOrderGoods goods = goodsList.get(0);


        return goods;
    }

    @Override
    public SubmitVo submit(OrderSubmitBo bo) {

        if (bo.getCartId() == 0) {

            MarketCartExample example = new MarketCartExample();

            MarketCartExample.Criteria criteria = example.createCriteria();

            criteria.andCheckedEqualTo(true);

            List<MarketCart> marketCarts = cartMapper.selectByExample(example);

            bo.setCartId(marketCarts.get(0).getId());
        }



        MarketOrder order = new MarketOrder();

        MarketAddress address = addressMapper.selectByPrimaryKey(bo.getAddressId());
        String province = address.getProvince();
        String city = address.getCity();
        String county = address.getCounty();
        String addressDetail = address.getAddressDetail();
        String resultAddress=province+city+county+addressDetail;


        order.setAddress(resultAddress);

        // 拿到username
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");

        MarketUserExample userExample = new MarketUserExample();

        MarketUserExample.Criteria userExampleCriteria = userExample.createCriteria();

        userExampleCriteria.andUsernameEqualTo(username);

        List<MarketUser> marketUsers = userMapper.selectByExample(userExample);

        MarketUser marketUser = marketUsers.get(0);

        Integer userId = marketUser.getId();

        order.setUserId(userId);

        Short sta=201;
        order.setOrderStatus(sta);

        long sn = System.currentTimeMillis();
        String orderSn=sn+"";
        order.setOrderSn(orderSn);
        order.setConsignee(address.getName());
        order.setMobile(address.getTel());


        order.setMessage(bo.getMessage());

        MarketCart cart = cartMapper.selectByPrimaryKey(bo.getCartId());

        Integer goodsId = cart.getGoodsId();
        String goodsName = cart.getGoodsName();

        MarketGoods goods = goodsMapper.selectByPrimaryKey(goodsId);

        order.setGoodsPrice(goods.getRetailPrice());
        BigDecimal bigDecimal = new BigDecimal("0");
        order.setFreightPrice(bigDecimal);
        order.setOrderPrice(goods.getRetailPrice());
        order.setCouponPrice(bigDecimal);
        order.setIntegralPrice(bigDecimal);
        order.setGrouponPrice(bigDecimal);
        order.setActualPrice(goods.getRetailPrice());


        orderMapper.insertSelective(order);

        MarketOrderGoods orderGoods = new MarketOrderGoods();

        orderGoods.setOrderId(order.getId());

        orderGoods.setGoodsId(goodsId);

        orderGoods.setGoodsName(goodsName);

        orderGoods.setGoodsSn(goods.getGoodsSn());

        //
        orderGoods.setProductId(0);

        orderGoods.setNumber(cart.getNumber());

        orderGoods.setPrice(goods.getRetailPrice());

        orderGoods.setPicUrl(goods.getPicUrl());

        orderGoods.setAddTime(new Date());

        orderGoods.setUpdateTime(new Date());

        orderGoods.setSpecifications(new String[0]);

        orderGoodsMapper.insertSelective(orderGoods);

        SubmitVo vo = new SubmitVo();

        vo.setGrouponLinkId(0);
        vo.setOrderId(order.getId());

        MarketCart marketCart = new MarketCart();
        marketCart.setId(bo.getCartId());
        marketCart.setDeleted(true);
        cartMapper.updateByPrimaryKeySelective(marketCart);

        return vo;
    }
}
